<template>
  <div>
    区块寻宝{{ state }}
    <div class="map-container">
      <div id="container" style="width: 100%; height: 600px"></div>
    </div>
    <button type="button" @click="绘制区块()">绘制区块</button>
  </div>
</template>
<script>
import { bus } from '@/main.js';
import { mapState, mapMutations } from 'vuex';

import mixinMap from '@/mixin/map';
import { Polygon } from '@/assets/map.js';

let gif = require('@/assets/gif.gif');
console.log(
  '%c [ gif ]-18',
  'font-size:13px; background:pink; color:#bf2c9f;',
  gif
);

export default {
  name: 'RegionalTreasureHunt', //区块寻宝
  mixins: [mixinMap], //混入
  components: {}, //组件
  props: {}, //集成属性
  data() {
    return {
      geolocation: null,
      MAPSTYLE: 'amap://styles/blue',
      CZOOM: 14,
      arrPolygon: [],
      state: '大区块模式', //【大区块模式，小店面模式】
      cMarker: null,
    };
  },
  computed: {
    ...mapState(['cusInfo']),
    comPolygon: function() {
      let MAP = this.map;
      return this.arrPolygon.map((item) => {
        let polygon = new AMap.Polygon({
          path: item.path,
          strokeColor: '#FF33FF',
          strokeOpacity: 0.6,
          strokeWeight: 3,
          fillColor: '#1791fc',
          fillOpacity: 0.6,
          zIndex: 5,
        });
        let a = item.getRectByPolygon(MAP);
        let icon = new AMap.Icon({
          image: item.icon,
          imageSize: new AMap.Size(24, 24),
          // imageSize: new AMap.Size(a.width, a.height),
        });
        let marker = new AMap.Marker({
          position: new AMap.LngLat(a.lng, a.lat),
          offset: [12, 12],
          // content: p.name,
          label: {
            // content: `${p.name}`,
          },
          icon: icon,
          zIndex: 3,
        });
        return {
          polygon: polygon,
          marker: marker,
        };
      });
    },
  },
  methods: {
    ...mapMutations([]),
    test: function() {
      console.log('test');
    },
    formatDataPolygon: function(data) {
      let tar = this.arrPolygon;
      tar.splice(0, tar.length);
      data.forEach((item) => {
        let polygon = new Polygon({
          path: item.path,
          icon: item.icon,
        });
        tar.push(polygon);
      });
    },
    ajaxPolygon: function() {
      return this.$api
        .fetch区块列表()
        .then((res) => {
          if (res.code == 200 && res.data) {
            this.formatDataPolygon(res.data);
            return Promise.resolve(200);
          }
        })
        .catch((err) => {
          console.error(err);
        })
        .finally((_) => {});
    },
    ajaxArea: function() {
      return this.$api
        .fetch店面子集by区块()
        .then((res) => {
          if (res.code == 200 && res.data) {
            let tar = this.arrPolygon;
            tar.splice(0, tar.length);
            res.data.forEach((item) => {
              let polygon = new Polygon({
                path: item.path,
                icon: item.icon,
              });
              tar.push(polygon);
            });
            return Promise.resolve(res);
          }
        })
        .catch((err) => {
          console.error(err);
        })
        .finally((_) => {});
    },
    绘制区块: function() {
      this.map.clearMap();
      let arr = this.comPolygon;
      let zoom = this.map.getZoom();
      console.log(
        '%c [ zoom ]-126',
        'font-size:13px; background:pink; color:#bf2c9f;',
        zoom
      );
      if (zoom < 15) {
        this.state = '大区块模式';
      }

      arr.forEach((item) => {
        let marker = zoom > this.CZOOM ? item.polygon : item.marker;
        marker.on('click', (e) => {
          let bounds = item.polygon.getBounds();
          this.map.setBounds(bounds, true);
          this.state = '小店面模式';
        });
        this.map.add(marker);
      });
    },
    updateMarkerToCenter() {
      let Map = this.map;
      this.map.clearMap();
      var center = Map.getCenter();
      let marker = this.cMarker;
      // 如果标记不存在，则创建
      if (!marker) {
        marker = new AMap.Marker({
          position: center,
          map: Map,
          title: '中心点标记',
          icon: new AMap.Icon({
            image: gif,
            size: new AMap.Size(64, 64),
            imageSize: new AMap.Size(64, 64),
          }),
        });

        // 可选：添加信息窗口
        var infoWindow = new AMap.InfoWindow({
          content: '这里是地图的中心位置',
          offset: new AMap.Pixel(0, -30),
        });

        // 点击标记时显示信息窗口
        marker.on('click', function() {
          infoWindow.open(Map, marker.getPosition());
        });
      } else {
        // 如果标记已存在，则更新位置
        marker.setPosition(center);
      }
    },
  },
  beforeCreate: function() {},
  created: function() {},
  beforeMount: function() {},
  mounted: function() {
    // this.getCurrentLocation();
    this.initAMap()
      .then((map) => {
        map.setMapStyle(this.MAPSTYLE);
        this.getCurrentLocation();

        map.on('zoomend', (e) => {
          this.绘制区块();
        });
        map.on('moveend', (e) => {
          this.cMarker = null;
          this.updateMarkerToCenter();
        });
        return this.ajaxPolygon();
      })
      .then((res) => {
        console.log(
          '%c [ res ]-101',
          'font-size:13px; background:pink; color:#bf2c9f;',
          res
        );
        this.绘制区块();
      })
      .catch((err) => {
        console.error(err);
      })
      .finally((_) => {});
  },
  beforeUpdate: function() {},
  updated: function() {},
  beforeDestroy: function() {},
  destroyed: function() {},
};
</script>
<style lang="less" scoped></style>
